<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;

class Admin extends Controller {
	var $default_page_items = 30;
	public function _initialize() {
		$statics = APP_URL . "/public/";
		$this->assign("app_url", APP_URL);
		$this->assign("statics", $statics);
		$this->assign("css_path", $statics . "css/");
		$this->assign("img_path", $statics . "img/");
		$this->assign("js_path", $statics . "js/");

		$this->assign("whereData", []);
		$this->assign("default_page_items", $this->default_page_items);
		/* 读取数据库中的配置 */
		$config = cache('DB_CONFIG_DATA');
		if (!$config) {
			$config = model('Config')->lists();
			cache('DB_CONFIG_DATA', $config);
		}
		// print_r($config);
		config($config); //添加配置

		$controller = Request::instance()->controller();
		$action = Request::instance()->action();
		$url = strtolower($controller . "/" . $action);

		$uinfo = session("uinfo");
		if (!$uinfo) {
			$uinfo = cookie("uinfo");
		}
		if (!$uinfo && strtolower(Request::instance()->controller()) != 'login') {
			$this->redirect(url('login/index'));
		}
		$this->uinfo = $uinfo;
		$this->assign("uinfo", $uinfo);

		if (checkAdminRule($url, $this->uinfo['roleid']) === 'false') {
			echo json_encode(['status' => 0, 'msg' => '无权限访问']);
			exit();
		}

		$keywords = input("param.keywords");
		if ($keywords !== null) {
			$this->assign("keywords", $keywords);
		}
	}
	public function get_pages() {
		$model = input("post.model");
		$searchData = input("post.searchData/a");
		$whereData = input("post.whereData/a");
		$where = get_map($searchData, $whereData);
		$whereOr = get_or($searchData);
		return get_pages($model, $where, $whereOr);
	}
	public function data_show() {
		$model = input("param.model");
		$order = input("param.order/s");
		if (!$model) {
			$model = $this->model;
		}
		$whereData = input("param.whereData/s");
		$whereDatas = [];
		if ($whereData) {
			$whereData = explode('&', $whereData);
			foreach ($whereData as $v) {
				$r = explode('=', $v);
				$whereDatas[$r[0]] = $r[1];
			}
		}
		$page = input("param.page", 1);
		$limit = input("param.limit", $this->default_page_items);
		$db = model($model);
		$offset = ($page - 1) * $limit;
		list($list, $where) = $db->get_list([], $whereDatas, $limit, $offset, $order);
		$count = $db->where($whereDatas)->count();
		$return = [
			'code' => 0,
			'msg' => '',
			'count' => $count,
			'data' => $list,
		];
		return json($return);
	}
	public function data_show_where() {
		$page = input("param.page", 1);
		$order = input("param.order");
		$limit = input("param.limit", $this->default_page_items);
		$db = model($this->model);
		$offset = ($page - 1) * $limit;
		$whereMap = $this->get_where_map();
		$check_controller = Request::instance()->controller();
		if (!isset($whereMap['userid']) && $this->uinfo['roleid'] != 1 && $check_controller != 'Convert') {
			if ($check_controller != 'Lunbo') {
				$whereUserid = [];
				if ($check_controller == 'Memberbouns' && $this->uinfo['roleid'] == '6') {
					$tempids1 = model('AdminUser')->where('dealerid', $this->uinfo['userid'])->where('roleid', '9')->column('userid');
					$tempids2 = $db->where('userid', 'in', $tempids1)->column('userid');
					$whereMap['userid'] = ['in', $tempids2];
				} else {
					$whereMap = $whereUserid ? array_merge($whereMap, $whereUserid) : $whereMap;
				}
				// $whereUserid = $this->get_userids();
			}
		}
		list($list, $count) = $db->admin_get_list($offset, $limit, $whereMap, $order);
		$return = [
			'code' => 0,
			'msg' => '',
			'count' => $count,
			'data' => $list,
		];
		return json($return);
	}
	protected function get_userids() {
		$dealer = input('param.dealer');
		$whereDatas = [];
		if ($dealer) {
			if ($this->uinfo['roleid'] != 1) {
				$dealers = model('AdminUser')->get_all_dealerids($this->uinfo['userid'], $this->uinfo['roleid']);
				$whereDatas['userid'] = ['in', $dealers];
			}
		} else {
			if ($this->uinfo['roleid'] != 1) {
				$userids = model("AdminUser")->get_all_userids($this->uinfo['userid'], $this->uinfo['roleid']);
				$whereDatas['userid'] = ['in', $userids];
			}
		}
		return $whereDatas;
	}
	public function data_save() {
		$model = input("post.model");
		if (!$model) {
			$model = $this->model;
		}
		$db = model($model);
		$postData = input("post.postData");
		parse_str($postData, $dataarr);
		// trace('exit');exit();
		trace($dataarr);
		$id = $db->save_data($dataarr);
		if ($id === false) {
			return json(['status' => 0, 'msg' => $db->getError()]);
		}
		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function data_delete() {
		$items = input("param.items");
		$items = trim($items, ",");
		$model = input("param.model");

		$db = model($model);
		$db->delete_data(['item_ids' => $items]);

		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function set_field() {
		$db = model($this->model);
		$postData = input("post.");
		$id = $db->where('id', $postData['id'])->setField($postData['field'], $postData['value']);
		// trace($db->getError());
		if ($id === false) {
			return json(['status' => 0, 'msg' => $db->getError()]);
		}
		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function data_update() {
		$model = input("post.model");
		if (!$model) {
			$model = $this->model;
		}
		$db = model($model);
		$postData = input("post.postData");
		parse_str($postData, $dataarr);
		trace($dataarr);
		$id = $db->update_data($dataarr);
		// trace($db->getError());
		if ($id === false) {
			return json(['status' => 0, 'msg' => $db->getError()]);
		}
		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function data_cache() {
		$db = model($this->model);
		$db->cache_data();
		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function index() {
		$getData = input('param.');
		$whereData = '';
		if ($getData) {
			foreach ($getData as $k => $v) {
				if (!$whereData) {
					$whereData .= $k . '=' . $v;
				} else {
					$whereData .= '&' . $k . '=' . $v;
				}
			}
		}
		$this->assign('keywords', isset($getData['keywords']) ? $getData['keywords'] : '');
		$this->assign("whereData", $whereData);
		return $this->fetch();
	}
	public function add() {
		return $this->fetch();
	}
	public function edit() {
		$items = input("param.items");
		$items = trim($items, ",");
		$model = input("param.model");
		if (!$model) {
			$model = $this->model;
		}
		$db = model($model);
		$info = $db->get_data(['item_id' => $items]);
		$this->assign("info", $info);
		return $this->fetch();
	}
	public function upload(Request $request) {
		// 获取表单上传文件
		$file = $request->file('Filedata');
		if (empty($file)) {
			$data = ['status' => 0, 'message' => '请选择上传文件'];
			return json($data);
		}
		// 移动到框架应用根目录/public/uploads/ 目录下
		$info = $file->validate(['size' => 1024 * 1024 * 1024, 'ext' => 'jpg,png,gif,mp4,apk'])->move(ROOT_PATH . 'upload' . DS);
		if ($info) {
			$data = ['status' => 1, 'message' => '', 'filepath' => '/upload/' . $info->getSaveName()];
			return json($data);
		} else {
			// 上传失败获取错误信息
			$data = ['status' => 0, 'message' => $file->getError()];
			return json($data);
		}
	}
	//排序
	public function setorder() {
		$listorders = $_POST['listorders'];
		$model = input("param.model");
		$db = model($model);
		foreach ($listorders as $id => $order) {
			$db->where('id', $id)->setField("listorder", $order);
		}
		return json(['status' => 1, 'msg' => '操作成功']);
	}
	public function data_export() {
		$fields = input("get.fields");
		$header = input("get.header");
		$title = input("get.filename");
		$page = input("param.page", 1);
		$limit = input("param.limit", $this->default_page_items);
		$offset = ($page - 1) * $limit;
		$searchData = $this->get_where_map();
		if (!isset($searchData['userid']) && $this->uinfo['roleid'] != 1) {
			$whereUserid = [];
			$searchData = $whereUserid ? array_merge($searchData, $whereUserid) : $searchData;
		}
		$db = model($this->model);
		$a = input("param.");
		$arr = [];
		if (isset($a['start_time'])) {
			if ($a['start_time']) {
				$arr['addtime'] = ['between', [strtotime($a['start_time']), strtotime($a['end_time'])]];
				$searchData = array_merge($searchData, $arr);
			}
		}
		list($list, $count) = $db->admin_get_list(0, 0, $searchData);
		$fieldarr = explode(",", trim($fields, ","));
		$fieldarrs = [];
		$colums = 0;
		foreach ($fieldarr as $v) {
			$condition_field = $condition_value = '';
			$field = $v;
			if ($field == 'sys_manage') {
				continue;
			}

			if (strpos($v, "|") !== false) {
				$varr = explode("|", $v);
				$conditionarr = explode(":", $varr[1]);
				$field = $varr[0];
				$condition_field = $conditionarr[0];
				$condition_value = $conditionarr[1];
			}
			$fieldarrs[$field] = [
				'field' => $field,
				'condition_value' => $condition_value,
				'condition_field' => $condition_field,
			];
			$colums++;
		}
		$lists = [];
		foreach ($list as $k => $v) {
			foreach ($fieldarrs as $vf) {
				if (strpos($vf['field'], ".") !== false) {
					$fieldarr = explode(".", $vf['field']);
					$v[$vf['field']] = $v[$fieldarr[0]][$fieldarr[1]];
				}
			}
			$lists[] = $v;
		}
		$datalist = [];
		foreach ($lists as $v) {
			$datas = [];
			foreach ($fieldarrs as $vf) {
				// if (!isset($v[$vf['field']])) {
				// 	continue;
				// }
				$datas[] = ['value' => $v[$vf['field']]];
			}
			$datalist[] = $datas;
		}
		$header = trim($header, ",");
		$headerarr = explode(",", $header);
		$excel_data = array(
			'username' => '',
			'title' => $title,
			'filename' => $title,
			'colums' => $colums,
			'colum_header' => $headerarr,
			'datalist' => $datalist,
		);
		set_excel($excel_data, 1, $title);
	}
}